package com.lungle.warmdiary.app.utils;


import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;

import com.lungle.warmdiary.app.api.remote.ApiFactory;
import com.lungle.warmdiary.app.base.BaseSubscriber;
import com.lungle.warmdiary.app.model.Result;
import com.lungle.warmdiary.app.model.response.Update;
import com.lungle.warmdiary.app.ui.dialog.DialogHelper;
import com.lungle.warmdiary.app.ui.dialog.WaitDialog;

import java.lang.ref.WeakReference;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class UpdateManager {

    private Update mUpdate;

    private WeakReference<Context> mContext;

    private boolean isShow = false;

    private WaitDialog mWaitDialog;


    public UpdateManager(Context context, boolean isShow) {
        mContext = new WeakReference<>(context);
        this.isShow = isShow;
    }

    public boolean haveNew() {
        if (this.mUpdate == null || TextUtils.isEmpty(mUpdate.getUrl())) {
            return false;
        }
        boolean haveNew = false;
        int curVersionCode = TDevice.getVersionCode();

        if ((mUpdate.getVersion() > curVersionCode)) {

            haveNew = true;
        }
        return haveNew;
    }

    public void checkUpdate() {
        if (isShow) {
            showCheckDialog();
        }
        ApiFactory.getBaseApi().checkUpdate(TDevice.getVersionCode()).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<Result<Update>>() {
                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        hideCheckDialog();
                        if (isShow) {
                            showFaileDialog();
                        }
                    }

                    @Override
                    public void onNext(Result<Update> updateResult) {
                        hideCheckDialog();
                        mUpdate = updateResult.getData();
                        onFinshCheck();
                    }
                });
    }

    private void onFinshCheck() {
        if (haveNew()) {
            showUpdateInfo();
        } else {
            if (isShow) {
                showLatestDialog();
            }
        }
    }

    private void showCheckDialog() {
        if ((mContext.get() == null))
            return;
        if (mWaitDialog == null) {
            mWaitDialog = DialogHelper.getWaitDialog((Activity) mContext.get(),
                    "正在检查更新...");
        }
        mWaitDialog.show();
    }

    private void hideCheckDialog() {
        if (mWaitDialog != null) {
            mWaitDialog.dismiss();
        }
    }

    private void showUpdateInfo() {
        if (mUpdate == null || mContext.get() == null) {
            return;
        }


        AlertDialog.Builder dialog = DialogHelper.getMessageDialog(mContext.get(), "当前存在新版本，请及时更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

                UIHelper.openSysBrowser(mContext.get(), mUpdate.getUrl());

                //                UIHelper.openDownLoadService(mContext.get(), mUpdate.getUrl(), "有新版本");


            }
        });
        dialog.setCancelable(false);
        dialog.setTitle("发现新版本");
        dialog.show();

    }

    private void showLatestDialog() {
        if (mContext.get() == null) return;
        DialogHelper.getMessageDialog(mContext.get(), "已经是新版本了").show();
        ;
    }

    private void showFaileDialog() {
        if (mContext.get() == null)
            DialogHelper.getMessageDialog(mContext.get(), "网络异常，无法获取新版本信息").show();
    }
}
